#pragma once

#include "my_Lock.hpp"
#include <filesystem>
#include <fstream>
#include <time.h>
#include <sstream>
#include<unistd.h>
#include<memory>

using namespace LockModule;

namespace LogMoudle
{
    
    // 默认的日志路径和日志文件名称
    const std::string defaultLogPath = "./Log/";
    const std::string defaultLogFile = "log.txt";

    // 默认的日志等级
    enum class Logevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    // 将日志等级转化为字符串
    std::string LogLevelTransform(Logevel level)
    {
        switch (level)
        {
        case Logevel::DEBUG:
            return "DEBUG";
        case Logevel::INFO:
            return "INFO";
        case Logevel::WARNING:
            return "WARNING";
        case Logevel::ERROR:
            return "ERROR";
        case Logevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    // 获取当前时间，将其转化为字符串
    std::string Get_Time()
    {
        time_t tm = time(nullptr);
        struct tm curr;
        localtime_r(&tm, &curr);
        char timebuffer[1024];
        snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr.tm_year + 1900,
                 curr.tm_mon,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);
        return timebuffer;
    }

    // 两种策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 控制台策略
    class ConsoleStrategy : public LogStrategy
    {
    public:
        void SyncLog(const std::string &message)
        {
            LockModule::LockGuard Lock(mt);
            std::cerr << message << std::endl;
        }
        ~ConsoleStrategy()
        {
            std::cout << "控制台策略关闭" << std::endl;
        }

    private:
        Mutex mt;
    };

    // 文件日志策略
    class FileStrategy : public LogStrategy
    {
    public:
        FileStrategy(std::string Filename = defaultLogFile, std::string Path = defaultLogPath)
        {
            _FileName = Filename;
            _Path = Path;
            if (std::filesystem::exists(_Path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_Path);
            }
            catch (const std::exception &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        void SyncLog(const std::string &message)
        {
            LockModule::LockGuard Lock(mt);
            std::string log = _Path + _FileName;
            std::ofstream out(log.c_str(), std::ios::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }
        ~FileStrategy()
        {
            std::cout << "文件策略关闭" << std::endl;
        }

    private:
        Mutex mt;
        std::string _FileName;
        std::string _Path;
    };

    // 具体的日志内容的实现
    class Logger
    {
    public:
        Logger()
        {
            UseConsoleStrategy();
        }
        void UseConsoleStrategy()
        {
            _strategy=std::make_unique<ConsoleStrategy>();
        }
        void UseFileStrategy()
        {
            _strategy=std::make_unique<FileStrategy>();
        }
        ~Logger()
        {
        }

        class LogMessage
        {
        private:
            // 日志等级、时间、pid号、文件名
            // 行号、策略、拼接好的日志信息
            Logevel _level;
            std::string _cur_time;
            pid_t _pid;
            std::string _file_name;
            int _line;
            Logger &_logeer;
            std::string _loginfo;

        public:
            LogMessage(Logevel level, std::string &filename, int line, Logger &logger)
                : _level(level),
                  _cur_time(Get_Time()),
                  _pid(getpid()),
                  _file_name(filename),
                  _line(line),
                  _logeer(logger)
            {
                std::stringstream buffer;
                buffer << "[" << _cur_time << "]"
                       << "[" << LogLevelTransform(level) << "]"
                       << "[" << _pid << "]"
                       << "[" << _file_name << "]"
                       << "[" << _line << "]"
                       << "-";
                _loginfo = buffer.str();
                //std::cout<<_loginfo<<std::endl;
            }

            // 打印内容拼接
            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream buffer;
                buffer << info;
                _loginfo += buffer.str();
                return *this; // 返回当前对象，用于下次继续进行<<

            }

            ~LogMessage()
            {
               
                // 在最后销毁的时候进行打印
                if (_logeer._strategy)
                {
                    _logeer._strategy->SyncLog(_loginfo);
                }
            }
        };

        LogMessage operator()(Logevel evel, std::string filename, int line)
        {
            return LogMessage(evel, filename, line, *this);
        }

    private:
        std::unique_ptr<LogStrategy> _strategy;
    };
    
    Logger log;

#define LOG(evel) log(evel,__FILE__,__LINE__)
#define  ENABLE_CONSOLE_LOG() log.UseConsoleStrategy()
#define  ENABLE_FILE_LOG() log.UseFileStrategy()
}